#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstdlib>
#include <cstring>
using namespace std;
// 线程拥有独立的上下文、栈
// 线程是轻量级进程，是进程的一个执行流
// 进程是资源分配的实体

// class Response
// {
// public:
//     int start_;
//     int end_;
//     string name_;

// public:
//     Response(int start, int end, const string &name) : start_(start), end_(end), name_(name)
//     {
//     }
// };

// class Request
// {
// public:
//     int result_;
//     int resultcode_;

// public:
//     Request(int result, int resultcode) : result_(result), resultcode_(resultcode)
//     {
//     }
// };
// void *sum(void *args)
// {
//     Response *res = static_cast<Response *>(args);
//     Request *rq = new Request(0, 0);
//     for (int i = res->start_; i <= res->end_; i++)
//     {
//         cout << res->name_ << " is runing, caling..., " << i << endl;
//         rq->result_ += i;
//     }
//     delete res;
//     return rq;
// }
// int main()
// {
//     Response *res = new Response(1, 100, "thread 1");
//     pthread_t tid;
//     pthread_create(&tid, NULL, sum, res);
//     void *ret;
//     pthread_join(tid, &ret);
//     Request *rq = static_cast<Request *>(ret);
//     cout << "main thread is quit" << ",ret: " << rq->result_ << endl;
//     delete rq;
//     return 0;
// }

string tohex(pthread_t tid)
{
    char bufer[64];
    snprintf(bufer, sizeof(bufer), "%p", tid);
    return bufer;
}
void *printfunc(void *args)
{
    int cnt = 5;
    while (true)
    {
        cout << "new thread pid: " << getpid() << "tid: " << tohex(pthread_self()) << endl;
        sleep(1);
        cnt--;
        if (cnt == 0)
            break;
    }
    pthread_exit((void *)1);
}
int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, printfunc, NULL);
    sleep(1);
    cout << "main thread pid:" << getpid() << endl;

    void *ret;
    pthread_join(tid, &ret);

    cout << "main thread is quit" << ",ret: " << (long long int)ret << endl;
}